﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web.Services.Description;
using System.Web.UI.WebControls;
using MPBlog.Core;
using MPBlog.DAL;
using MPBlog.Model;

namespace MPBlog.UserControls
{
    /// <summary>
    /// widget存放容器
    /// </summary>
    public partial class WidgetZoneContainer : System.Web.UI.UserControl
    {
        //用于存放所有的WidgetZone及其对应的子widget信息，无论WidgetZone有几个，这个只有一个
        //这样可以避免每次都从数据库取数据
        private static Dictionary<string, List<Model.Widget>> widgetZones;
        private static Dictionary<string, List<Model.Widget>> WidgetZones
        {
            get { return widgetZones ?? (widgetZones = new WidgetZoneDao().GetAllZones()); }
        }

        private string zoneName = "defaultZone";  //默认为defaultZone
        /// <summary> 
        /// 区域的名字（标志)
        /// </summary> 
        public string ZoneName
        {
            get
            {
                return zoneName;
            }

            set { zoneName = value; }
        }

        /// <summary>
        /// 重置widgetzone缓存
        /// </summary>
        public static void ResetWidgetZoneCache()
        {
            widgetZones = null;
        }

        /// <summary> 
        /// 这个zone包含的子widgets信息 
        /// </summary> 
        private List<Widget> Widgets
        {
            get { return WidgetZones.ContainsKey(ZoneName) ? WidgetZones[ZoneName] : new List<Widget>(); }
        }

        protected override void OnLoad(EventArgs e)
        {
            btnAddWidget.OnClientClick = string.Format("if(!MPBlog.validate.addWidget('{0}')){{return false;}}",
                                                      ddlWidgets.ClientID);


            //绑定widget添加数据源
            if (!IsPostBack)
            {
                ddlWidgets.Items.Add(new ListItem("-添加小部件-"));
                var di = new DirectoryInfo(Page.Server.MapPath(string.Format("{0}widgets", Utils.RelativeWebRoot)));
                foreach (
                    var dir in di.GetDirectories().Where(dir => File.Exists(Path.Combine(dir.FullName, "widget.ascx"))))
                {
                    ddlWidgets.Items.Add(new ListItem(dir.Name));
                }
            }

            //将取出的每个widget控件写入 
            if (Widgets == null)
            {
                return;
            }

            //加载此zone中的每个widget
            foreach ( Widget widget in Widgets)
            {
                var fileName = string.Format("{0}Widgets/{1}/Widget.ascx", Utils.RelativeWebRoot, widget.Name);
                try
                {
                    //加载特定的控件，控件类型为WidgetBase（因为每个控件都继承了WidgetBase） 
                    var control = (WidgetBase)Page.LoadControl(fileName);

                    //从读取的xml属性中将值复制给control属性 
                    control.WidgetId = widget.WidgetId;
                    control.ID = widget.WidgetId.ToString().Replace("-", string.Empty);  //必须指定ID，否则可能出现重复的控件ID
                    control.ShowTitle = control.IsEditable ? widget.ShowTitle : control.DisplayHeader;
                    control.Zone = zoneName;

                    control.LoadWidget();

                    //将此控件包装到widgetContainer里面，这样每个control都有一个统一的外观（修改，删除按钮在这里统一） 
                    var widgetContainer = WidgetContainerBase.GetWidgetContainer(control);
                    //将包装好的widget加入这个zone中 
                    Controls.Add(widgetContainer);
                }
                catch
                {
                    //找不到则不加载 
                }
            }

            base.OnLoad(e);
        }

        protected void btnAddWidgetClick(object sender, EventArgs e)
        {
            string widgetName = ddlWidgets.SelectedValue;
            if (widgetName == "-添加小部件-")
            {
                Page.Message("请选择小部件",Utils.MessageType.error,3000);
                return;
            }


            WidgetZoneDao widgetZoneDao = new WidgetZoneDao();

            int maxDispalyIndex = GetMaxDisplayIndex();

            WidgetZone widgetZone = new WidgetZone
                                        {
                                            ZoneName = zoneName,
                                            ShowTitle = true,
                                            WidgetGuid = Guid.NewGuid().ToString(),
                                            DisplayIndex = maxDispalyIndex + 1,
                                            WidgetName = widgetName,
                                        };
            widgetZoneDao.Create(widgetZone);
            ResetWidgetZoneCache();
            Response.Redirect(Request.Path);
        }

        /// <summary>
        /// 从缓存中找到这个zone下最大的显示序号
        /// </summary>
        /// <returns></returns>
        private int GetMaxDisplayIndex()
        {
            if (Widgets == null)
            {
                throw new NullReferenceException("zone必须有widgets");
            }
            if (Widgets.Count == 0)
            {
                return 0;
            }
            else
            {
                return Widgets.Max(t => t.DisplayIndex);
            }
        }
    }
}